package server

import (
	"net"
	"strings"
)

type User struct {
	Name   string
	Addr   string
	C      chan string
	conn   net.Conn
	server *Server
}

func NewUser(conn net.Conn, server *Server) *User {
	userAddr := conn.RemoteAddr().String()

	user := &User{
		Name:   userAddr,
		Addr:   userAddr,
		C:      make(chan string),
		conn:   conn,
		server: server,
	}

	go user.ListenMessage()

	return user
}

func (user *User) Online() {
	user.server.MapLock.Lock()
	user.server.OnlineMap[user.Name] = user
	user.server.MapLock.Unlock()

	user.server.BroadCast(user, "已上线")
}

func (user *User) Offline() {
	user.server.MapLock.Lock()
	delete(user.server.OnlineMap, user.Name)
	user.server.MapLock.Unlock()
	user.server.BroadCast(user, "下线")
}

func (user *User) SendMsg(msg string) {
	user.conn.Write([]byte(msg))
}

func (user *User) DoMessage(msg string) {
	if msg == "who" {
		user.server.MapLock.Lock()
		{
			for _, u := range user.server.OnlineMap {
				message := "[" + u.Name + "]" + "在线...\n"
				user.SendMsg(message)
			}
		}
		user.server.MapLock.Unlock()
	} else if len(msg) >= 6 && msg[:6] == "rename" {
		idx, n := 6, len(msg)

		for ; idx < n; idx++ {
			if msg[idx] == ' ' {
				continue
			} else {
				break
			}
		}

		if idx == n {
			user.SendMsg("用户名不能为空\n")
		} else {
			userName := msg[idx:]
			user.server.MapLock.Lock()
			{
				_, ok := user.server.OnlineMap[userName]
				if ok {
					user.SendMsg("用户名已存在\n")
				} else {
					delete(user.server.OnlineMap, user.Name)
					user.Name = userName
					user.server.OnlineMap[userName] = user
					user.SendMsg("用户名已修改为: " + userName + "\n")
				}
			}
			user.server.MapLock.Unlock()
		}
	} else if len(msg) >= 4 && msg[:4] == "send" {
		sender := strings.SplitN(msg, " ", 3)[1:] // send user mseeage
		remoteName := sender[0]

		if remoteUser, ok := user.server.OnlineMap[remoteName]; ok {
			if sender[1] == " " {
				user.SendMsg("消息不能为空!\n")
			} else {
				remoteUser.SendMsg(user.Name + "对你说: " + sender[1] + "\n")
			}
		} else {
			user.SendMsg("用户名不存在\n")
		}

	} else {
		user.server.BroadCast(user, msg)
	}
}

// 监听 channel 的写入
func (user *User) ListenMessage() {
	for {
		msg := <-user.C

		user.conn.Write([]byte(msg + "\n"))
	}
}
